import { Mask, Toast } from 'antd-mobile'
import { WbZongList, OpenZongGiff } from '../../../api/active'
import './index.less'
import { useState } from 'react'
import { useEffect } from 'react'

export default function DragonTask() {
  const [reopenVisible, setReopenVisible] = useState(false)
  const [rewardVisible, setRewardVisible] = useState(false)
  const [taskList, setTaskList] = useState([])

  const [pointList, setPointList] = useState([]) // 任务进度
  const [getNum, setGetNum] = useState(0)
  let totalNum = 100

  // {
  // 	"id": 7,
  // 	"name": "完成上述全部任务",
  // 	"need_num": 1,
  // 	"complete_num": "1",
  // 	"reward_num": 10
  // }
  const getData = () => {
    WbZongList().then((res) => {
      console.log(res)
      setPointList(
        res.data.list?.map((item) => ({
          point: item.point,
          id: item.id,
          is_open: item.is_open
        }))
      )
      setGetNum(res.data?.my_zong_num || 0)
      setTaskList(res.data?.task_info)
      if (res.data.task_info) {
        // 计算总数
        // eslint-disable-next-line react-hooks/exhaustive-deps
        totalNum = res.data.task_info.reduce((prev, cur) => (cur?.need_num || 0) + prev, 0)
        console.log('计算总数', totalNum)
      }
    })
  }
  useEffect(() => {
    getData()
  }, [reopenVisible, rewardVisible])

  const [selectId, setSelectId] = useState('')
  const openReward = (item) => {
    console.log(item)
    // 没到数量
    if (item.point > getNum) return false
    // 已经开过
    if (item.is_open) return false

    console.log('打开了嘛')
    setSelectId(item.id)
    setReopenVisible(true)
  }

  const [rewardItem, setRewardItem] = useState({ name: '', img: '' })
  const openZongZi = () => {
    Toast.show({
      content: '开奖中',
      icon: 'loading',
      maskClickable: false
    })
    OpenZongGiff({
      zong_id: selectId
    })
      .then((res) => {
        Toast.clear()
        setRewardItem(res.data)
        setReopenVisible(false)
        setRewardVisible(true)
      })
      .catch((err) => {
        Toast.show({
          content: err.message,
          position: 'bottom'
        })
      })
  }

  const findData = () => {
    // 1 => 15% 3 => 66%
    // 2 => 40% 4 => 91%
    if (!pointList?.length) return '0%'
    const score = ['15%', '40%', '66%', '91%']
    const d = JSON.parse(JSON.stringify(pointList))
    console.log(d)
    let idx = -1
    d.forEach((res, i) => {
      console.log(i, getNum)
      if (getNum >= d[i].point) {
        idx = i
      }
    })
    console.log('score', idx)
    if (idx !== -1) {
      return score[idx]
    } else {
      return '0%'
    }
  }

  return (
    <div className="drangon_task">
      <div className="boat_wrap">
        <div className="time_wrap">活动时间：6月21日09:00-7月2日23:59:59</div>
        <div className="rule_btn" onClick={() => document.getElementsByClassName('rule_box')[0].scrollIntoView()}>
          活动规则
        </div>
        <div className="box reward_box">
          <div className="title"></div>
          <div className="reward_level">
            {pointList.length
              ? pointList.map((item) => (
                  <div className={`item ${+item?.point > +getNum ? 'disable' : ''}`}>
                    <div className={`tag`} onClick={() => openReward(item)}>
                      {+item?.point > +getNum ? '等待开启' : item.is_open ? '已开启' : '立刻开启'}
                    </div>
                    <div className="icon"></div>
                  </div>
                ))
              : ['', '', '', '', ''].map(() => (
                  <div className="item disable">
                    <div className="tag">立刻开启</div>
                    <div className="icon"></div>
                  </div>
                ))}
          </div>
          <div className="prograss">
            <div className="bar"></div>
            <div className="score" style={{ width: findData() }}></div>
            <div className="points">
              {pointList.map((item) => (
                <div className="point">
                  <div className="circle"></div>
                  <div className="num">粽子{item.point}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="my_score">我的粽子：{getNum}</div>
        </div>
        <div className="box gift_box">
          <div className="title"></div>
          <div className="con">
            <div className="item">
              <div className="icon a"></div>
              <div className="text">龙舟争渡</div>
            </div>
            <div className="item">
              <div className="icon b"></div>
              <div className="text">有酒有粽</div>
            </div>
            <div className="item">
              <div className="icon c"></div>
              <div className="text">粽子节安康</div>
            </div>
          </div>
        </div>
        <div className="boat_task">
          <div className="title"></div>
          {taskList.map((item, idx) => (
            <div className="task_item" key={item.id}>
              <div className={`icon icon_${idx + 1}`}></div>
              <div className="info">
                <p className="tit">
                  {item.name} <span>{item.need_num ? `${item.complete_num}/${item.need_num}` : ''}</span>
                </p>
                <p className="send">粽子+{item.reward_num}</p>
              </div>
              <div
                className={`action_btn ${+item.complete_num === +item.need_num ? 'done' : 'active'}`}
              >{`${+item.complete_num === +item.need_num ? '已完成' : '未完成'}`}</div>
            </div>
          ))}
        </div>
        <div className="rule_box">
          <div>
            <div className="tit">活动时间</div>
            <div className="c">6月21日09:00-7月2日23:59:59</div>
          </div>
          <div style={{ marginTop: 16 }}>
            <div className="tit">玩法奖励</div>
            <div className="c">
              <p>
                1.在房间内赠送活动礼物，完成对应任务，获得粽子
                可用于开启龙粽礼包，每个龙粽礼包仅可开启一次，包厢内可开出期限永久道具，包括不限于：礼物道具，头像框，进场特效等等
              </p>
              <p>
                2."粽送好礼"旨在提升聊天室娱乐的互动性，本互动功能中所获得道具均不可进行撤销、退款或退换，不可兑换成
                {window.baseConfig.coin_name}、现金、不可再次交易；您承诺不使用本功能进行任何违反法律法规及本平台规则、规范的活动或行为；
              </p>
              <p>3.本活动最终解释权归{window.baseConfig.package_name}所有。</p>
            </div>
          </div>
        </div>
        <div className="reward_detail_box">
          <div className="tit">龙粽宝箱礼物列表</div>
          <div className="info">
            <p>
              <span>6月端阳（头像框）</span> <span>永久/期限</span>
            </p>
            <p>
              <span>端午龙舟特效</span> <span>永久</span>
            </p>
            <p>
              <span>惊喜盲盒</span> <span>永久/期限</span>
            </p>
          </div>
        </div>
      </div>

      <Mask visible={reopenVisible} onMaskClick={() => setReopenVisible(false)}>
        <div className="re_open_modal" onClick={openZongZi}>
          <div className="tit"></div>
          {/* animate__bounceInDown */}
          {/* {animate__repeat-2} */}
          <div className="reward_bg  animate__tada animate__animated"></div>
        </div>
      </Mask>
      <Mask visible={rewardVisible} onMaskClick={() => setRewardVisible(false)}>
        <div className="re_open_modal reward" onClick={() => setRewardVisible(false)}>
          <div className="content">
            <div className="item">
              <img src={rewardItem.img} alt={rewardItem.name} />
              <p className="name ellipsis1">
                {rewardItem.name}
                {rewardItem?.expire ? `(${rewardItem?.expire}/天)` : '永久'}
              </p>
            </div>
          </div>
        </div>
      </Mask>
    </div>
  )
}
